#!/usr/bin/env python

import os
import sys
import subprocess
import re
import time
import _thread
import common

icon_fg = common.black
icon_bg = common.blue
icon_tr = "0xff"
text_fg = common.black
text_bg = common.blue
text_tr = "0xff"

icon_color = "^c" + str(icon_fg) + "^^b" + str(icon_bg) + str(icon_tr) + "^"
text_color = "^c" + str(text_fg) + "^^b" + str(text_bg) + str(text_tr) + "^"
DELAY_TIME = 1

filename = os.path.basename(__file__)
name = re.sub(r"\..*", '', filename)

vol_text = "--"
vol_icon = "ﱝ"
volumuted = ""

def get_connected_bluetooth_device():
    """
    获取当前已连接的蓝牙设备地址
    返回: 蓝牙设备MAC地址字符串，如 '41:42:54:00:F3:40'，如果没有设备连接则返回None
    """
    try:
        # 方法1: 检查所有配对设备的连接状态
        cmd = "bluetoothctl paired-devices | awk '{print $2}'"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        
        if result.returncode == 0:
            devices = [d.strip() for d in result.stdout.split('\n') if d.strip()]
            for device in devices:
                # 检查每个设备是否已连接
                cmd = f"bluetoothctl info {device} | grep 'Connected: yes'"
                result = subprocess.run(cmd, shell=True, timeout=2, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
                if result.returncode == 0 and result.stdout.strip():
                    return device
        
        # 方法2: 检查默认音频输出是否为蓝牙设备
        cmd = "pactl info | grep 'Default Sink' | grep -i bluez"
        result = subprocess.run(cmd, shell=True, timeout=2, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        if result.returncode == 0:
            # 从sink名称中提取MAC地址
            sink_output = result.stdout.strip()
            mac_match = re.search(r'([0-9A-Fa-f:]{17})', sink_output)
            if mac_match:
                return mac_match.group(1)
        
        return None
        
    except subprocess.TimeoutExpired:
        return None
    except Exception as e:
        print(f"Error getting connected device: {e}")
        return None

def GetBluetoothBatteryByBluetoothctl():
    try:
        # 获取当前已连接的蓝牙设备地址
        device_address = get_connected_bluetooth_device()
        
        if not device_address:
            return "󱔑"  # 没有连接的蓝牙设备
        
        # 使用bluetoothctl命令获取电池信息
        cmd = f'bluetoothctl info {device_address} | grep -i "battery"'
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        output = result.stdout.strip()
        
        # 从输出中提取电池百分比
        battery_match = re.search(r'(\d+)%', output)
        if battery_match:
            battery_percent = int(battery_match.group(1))
            
            # 根据电量选择图标
            if battery_percent >= 95: icon = "󰥈"
            elif battery_percent >= 90: icon = "󰥆"
            elif battery_percent >= 80: icon = "󰥅"
            elif battery_percent >= 70: icon = "󰥄"
            elif battery_percent >= 60: icon = "󰥃"
            elif battery_percent >= 50: icon = "󰥂"
            elif battery_percent >= 40: icon = "󰥁"
            elif battery_percent >= 30: icon = "󰥀"
            elif battery_percent >= 20: icon = "󰤿"
            elif battery_percent >= 10: icon = "󰤾"
            else: icon = "󰥇"
            
            return f"{icon}{battery_percent}%"
        else:
            return "󱔑"  # 未找到电池信息
    
    except subprocess.TimeoutExpired:
        return "󱔑"  # 超时
    except Exception as e:
        print(f"Error getting battery: {e}")
        return "󱃓"  # 其他错误

def get_vol_content():
    global vol_text
    global vol_icon
    global volumuted

    try:
        cmd = "pactl info | grep 'Default Sink' | awk '{print $3}'"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        sink = str(result.stdout.replace('\n', ''))
        
        if not sink:
            vol_text = "--"
            vol_icon = "ﱝ"
            volumuted = ""
            bluetooth_battery = GetBluetoothBatteryByBluetoothctl()
            return f"{vol_icon}{vol_text}% {bluetooth_battery}"
        
        cmd = f"pactl list sinks | grep '{sink}' -A 6 | grep 'Mute:' | grep -q 'no'; echo $?"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        volumuted = (result.stdout.strip() == "0")
        
        cmd = f"pactl list sinks | grep '{sink}' -A 7 | grep 'Volume:' | head -1 | awk '{{printf int($5)}}'"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        vol_text = str(result.stdout.replace('\n', ''))
        
        if not volumuted:
            vol_text = "--"
            vol_icon = "ﱝ"
        else:
            try:
                vol = int(vol_text) if vol_text.isdigit() else 0
                if vol == 0: 
                    vol_icon = "婢"
                    vol_text = "00"
                else:
                    vol_icon = "墳 "
            except ValueError:
                vol_text = "--"
                vol_icon = "ﱝ"
        
        # 使用bluetoothctl方法获取蓝牙电池信息
        bluetooth_battery = GetBluetoothBatteryByBluetoothctl()
        
        return f"{vol_icon}{vol_text}% {bluetooth_battery}"
    
    except Exception as e:
        print(f"Error in get_vol_content: {e}")
        return f"ﱝ--% 󱔑"

def update(loop=False, exec=True):
    while True:
        try:
            icon = " " + get_vol_content() + " "
            txt = "^s" + str(name) + "^" + str(icon_color) + str(icon) + str(text_color)
            common.write_to_file(txt + "\n", str(name))
            if not loop:
                if exec:
                    os.system("xsetroot -name '" + str(txt).replace("'", "'\\''") + "'")
                break
            time.sleep(DELAY_TIME)
        except Exception as e:
            print(f"Error in update: {e}")
            time.sleep(DELAY_TIME)

def update_thread():
    _thread.start_new_thread(update, (False, False))

def notify(string=''):
    try:
        global vol_text
        global vol_icon
        global volumuted
        get_vol_content()

        cmd = ""
        if not volumuted:
            cmd = "notify-send -r 9527 '婢  mute'"
        else:
            cmd = f"notify-send -r 9527 -h int:value:{vol_text} -h string:hlcolor:#dddddd '{vol_icon} Volume'"
        os.system(cmd)
    except Exception as e:
        print(f"Error in notify: {e}")

def click(string=''):
    try:
        if string == 'L':
            notify()
        elif string == 'M':
            os.system("pactl set-sink-mute @DEFAULT_SINK@ toggle")
            notify()
        elif string == 'R':
            os.system("killall pavucontrol 2>/dev/null || pavucontrol --class floatingTerminal &")
        elif string == 'U':
            os.system("pactl set-sink-volume @DEFAULT_SINK@ +5%")
            notify()
        elif string == 'D':
            os.system("pactl set-sink-volume @DEFAULT_SINK@ -5%")
            notify()
    except Exception as e:
        print(f"Error in click: {e}")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == "update":
            pass
        elif sys.argv[1] == "notify":
            notify()
        else:
            update(exec=False)
            click(sys.argv[1])
            update(exec=False)
    else:
        update()
